function live_chat() {
	$('#live-chat').live_chat();
	
}

function init_live_chat() {
	live_chat();
	$('#live-chat-send').click(function() {
		var channel = $(this).attr('data-channel');
		var message = $('#live-chat-input').val();
		$('#live-chat-input').val('');
		if(message) {
			$.ajax({
    			url:'/modules/live-chat/live-chat-handler.php',
    			data:{
    				method:'post',
    				message:message,
    				channel:channel
    			},
    			success:function() {
    				live_chat();
    			},
    			type:'POST'
    		});
		}
	});
}

(function($){
	$.fn.live_chat = function(options) {
 		return this.each(function() {
 			var current = $(this);
 			var channel = $(this).attr('data-channel');
 			var limit = $(this).attr('data-limit');
 			var last = $(this).attr('data-last');
 			$.ajax({
    			url:'/modules/live-chat/live-chat-handler.php',
    			data:{
    				method:'read',
    				last:last,
    				limit:limit,
    				channel:channel
    			},
    			type:'POST',
    			dataType:'json',
    			error: function(a) {
    				alert(a);
    			},	
    			success: function(data) {
    				if(data.count) {
    					var length = current.children('li').length;
    					if(length == limit) {
							for(var i=1;i<=data.count;i++) {
								current.children('li:first').fadeOut().remove();
							}
						}
						current.append(data.chats);
						current.attr('data-last', data.last);
					}
					setTimeout('live_chat()', 5000);
    			}
    		});
 		});
 	};
})(jQuery);


